﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Beyondbit.Desktop.Common;
using RBS.Common;
using RBS.Common.JsonEntity;
using RBS.Core.Extension;
using RBS.Web.Hotel.Controllers;
using Webdiyer.WebControls.Mvc;

namespace RBS.Web.Hotel.Areas.Deed.Controllers
{
    public class CouponsController : BaseController
    {
        //
        // GET: /Deed/Advertising/

        public ActionResult Index()
        {
            return View();
        } 
        //list
        public ActionResult SendFoodPaymentList(int id = 1, string kword = null)
        {
             return View(PaymentList(1, id, kword));
        }
        public ActionResult ConsumptionPaymentList(int id = 1, string kword = null)
        {
             return View(PaymentList(2, id, kword));
        }
        public ActionResult AdvertitPaymentList(int id = 1, string kword = null)
        {
            return View(PaymentList(3, id, kword));
        }
        public PagedList<RBS.Core.Model.P_Advertis_Payment> PaymentList(int type = 0, int id = 1, string kword = null)
        {
             const int pageSize = 10; 
            var bll = new RBS.Core.BLL.P_Advertis_Payment(); 
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and HotelId=" + CurrentUser.HotelId + strTemp.ToString();
            if (type != 0)
            {
                strWhere+=" and DeedType=  " + type + "";
            } 
            const string orderby = " id  desc";
            var startIndex = id; 
            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
            PagedList<RBS.Core.Model.P_Advertis_Payment> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.P_Advertis_Payment>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.P_Advertis_Payment>();
                arts = new PagedList<RBS.Core.Model.P_Advertis_Payment>(list, id, pageSize, totalItems);
            }
            return arts;
        }
         
        //edit
        public ActionResult PaymentEdit(int id = 0)
        { 
            var model = new RBS.Core.Model.P_Advertis_Payment
                {
                    HotelId = CurrentUser.HotelId,
                    ValidStartTime = DateTime.Now.AddDays(1),
                    ValidEndTime = DateTime.Now.AddDays(2),
                    CreateTime=DateTime.Now
                }; 
            var action = Request["type"];
            if (action != null)
            {
                model.DeedType = (int)(RBSEnums.DeedType)Enum.Parse(typeof(RBSEnums.DeedType), action, false);
            }
            if (id != 0)
            { 
                var bll = new RBS.Core.BLL.P_Advertis_Payment();
                model = bll.GetModel(id);
            }
            ViewData.Model = model;
            return View();
        }
        [HttpPost]
        public ActionResult PaymentEdit(FormCollection collection)
        { 
            var a = collection;
            var model = new RBS.Core.Model.P_Advertis_Payment
            {
                Denomination = Convert.ToInt32(collection["Denomination"]),
                ValidStartTime = DateTime.Parse(collection["ValidStartTime"]),
                ValidEndTime = DateTime.Parse(collection["ValidEndTime"]),
                Quantity =   Convert.ToInt32(collection["Quantity"]),
                Crowd =  collection["Crowd"],
                AccessRules =  collection["AccessRules"],
                UseRules =  collection["UseRules"],
                IsCrossHotel =   Convert.ToInt32(collection["IsCrossHotel"]),
                HotelId =   Convert.ToInt32(collection["HotelId"]),
                UserId =   Convert.ToInt32(collection["UserId"]),
                CreateTime =   Convert.ToDateTime(collection["CreateTime"]),
                DeedType =    Convert.ToInt32(collection["DeedType"]),
            };

            var url = "";
            if (model.DeedType ==(int)RBSEnums.DeedType.Advertit)
            {
                model.DeedStatus =(int)RBSEnums.DeedStatus.Audit; 
            }
            else
            {
                model.DeedStatus = (int)RBSEnums.DeedStatus.Ok; 
            }
            var bll = new RBS.Core.BLL.P_Advertis_Payment();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model); 
            }
            else
            { 
               var apid= bll.Add(model);  
            }
            return RedirectToAction(DeedTypeReturnUrl(model.DeedType));
        } 

        public JsonResult GetCookBook(int cid)
        {
            var jet = new JsonReturnMessages();
            var model = new RBS.Core.BLL.Hotel.H_Hotel_Cookbook().GetModelByCache(cid);
            jet.IsSuccess = true;
            jet.Data = model.Name;
            return Json(jet, JsonRequestBehavior.AllowGet);
        } 
        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="id"></param>
        /// <param name="deedType"></param>
        /// <returns></returns>
        public ActionResult Obsolete(int id,int deedType)
        {
            var bll = new RBS.Core.BLL.P_Advertis_Payment();
            var model = bll.GetModel(id);
            model.DeedStatus = (int)RBSEnums.DeedStatus.Obsolete;
            new RBS.Core.BLL.P_Advertis_Payment().Update(model);
            return RedirectToAction(DeedTypeReturnUrl(deedType));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Obsolete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
          
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    var bll = new RBS.Core.BLL.P_Advertis_Payment();
                    var model = bll.GetModel(int.Parse(id));
                    model.DeedStatus = (int)RBSEnums.DeedStatus.Obsolete; 
                    new RBS.Core.BLL.P_Advertis_Payment().Update(model);
                    returnUrl = DeedTypeReturnUrl(model.DeedType); 
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            }
             
            ret.IsSuccess = true;
            ret.Msg = "操作成功";


            ret.Data = returnUrl;
            return Json(ret);
        }

        public string DeedTypeReturnUrl(int deedType )
        { 
            var returnUrl = "";
            switch (deedType)
            {
                case (int)RBSEnums.DeedType.SendFood:
                    returnUrl = "SendFoodPaymentList";
                    break;
                case (int)RBSEnums.DeedType.Consumption:
                    returnUrl = "ConsumptionPaymentList";
                    break;
                case (int)RBSEnums.DeedType.Advertit:
                    returnUrl = "AdvertitPaymentList";
                    break;
            }
            return returnUrl;
        }  

        #region 赠与 
        public ActionResult GiftUser(int apid)
        {
            var model = new RBS.Core.Model.P_Advertis_Batch
                {
                    AP_Id = apid
                };
            ViewBag.lave =  new RBS.Core.BLL.P_Advertis_Batch().GetLave(apid);
            return View(model);
        }
        [HttpPost]
        public ActionResult GiftUser(FormCollection collection)
        {
            var num = Convert.ToInt32(collection["Num"]);
              var apId = Convert.ToInt32(collection["AP_Id"]);
            if (num > 0)
            {
              
                var userId = Convert.ToInt32(collection["U_ID"]);
                for (int i = 0; i < num; i++)
                {
                    AddBatch(apId, userId);
                }
            }

            return RedirectToAction("GiftUserList", new { apid = apId });
        }

        public void AddBatch(int apId,int userId)
        {
            var model = new RBS.Core.Model.P_Advertis_Batch
                {
                    AP_Id = apId,
                    BatchTime = DateTime.Now,
                    ABStatus = (int) RBSEnums.DeedStatus.Ok,
                    BatchNo =Utils.GetGuid()
                };
            var bll = new RBS.Core.BLL.P_Advertis_Batch();
            var abid = bll.Add(model); 
            var user = new RBS.Core.Model.P_Advertis_List
                {
                    AB_Id = abid,
                    U_Id = userId,
                    ALStatus = (int) RBSEnums.DeedStatus.Ok,
                    ALTime = DateTime.Now
                };
            var userbll = new RBS.Core.BLL.P_Advertis_List();
            userbll.Add(user);
        } 
        public ActionResult GiftUserList(int apid, int id = 1, string kword = null)
        {
            ViewBag.Action = Request["action"];
            const int pageSize = 10;
            ViewBag.apid = apid;
            var bll = new RBS.Core.BLL.P_Advertis_Batch();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and  ap_id= "+ apid+ strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.V_BatchList>(dt);
            PagedList<RBS.Core.Model.V_BatchList> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.V_BatchList>(list, id, pageSize, totalItems);
            else
            {
                return RedirectToAction("GiftUser",new{apid=apid});
            }
            return View(arts);
        }
        #endregion



        #region 优惠券API

        /// <summary>
        /// 获取酒店优惠券
        /// </summary> 
        /// <param name="hid"></param>
        /// <returns></returns> 
        public JsonResult SelectDeedList(int hid = 0)
        {
            JsonData jsonData = ApiRepository.Get("api/Deed/HotelDeed?hotelid=" + hid);
            return Json(jsonData,JsonRequestBehavior.AllowGet);  
        } 
        /// <summary>
        /// 赠与用户
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="apid"></param>
        /// <param name="num"></param>
        /// <returns></returns> 
        public JsonResult Gift(int uid, int apid, int num = 1)
        {
            JsonData jsonData = ApiRepository.Get("api/Deed/HotelDeed?uid=" + uid + "&apid=" + apid + "&num=" + num);
            return Json(jsonData, JsonRequestBehavior.AllowGet);  
        }
        #endregion

    }
}
